import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { NzTreeFlatDataSource, NzTreeFlattener } from 'ng-zorro-antd/tree-view';
import { Router } from '@angular/router';
import { MenuService } from '@/service/menu.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Menu } from '@/models/Menu';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { DialogInputComponent } from '@/pages/comps/dialog-input/dialog-input.component';
import { ApiResponse } from '@/models/ApiResponse';
import { Observable } from 'rxjs';
interface FlatNode {
  expandable: boolean;
  id: number;
  name: string;
  level: number;
  disabled: boolean;
  icon?: string;
  url?: string;
}

@Component({
  selector: 'app-menulist',
  templateUrl: './menulist.component.html',
  styleUrls: ['./menulist.component.less']
})

export class MenulistComponent implements OnInit {

  dataSet: any = []
  indeterminate: boolean = false;
  isInputDirVisible: boolean = false;

  // treeview component
  private transformer = (node: Menu, level: number): FlatNode => ({
    id: node.menu_id,
    expandable: !!node.children && node.children.length > 0,
    name: node.menu_name,
    level,
    disabled: false,
    icon: node.menu_icon,
    url: node.menu_path,
  });
  selectListSelection = new SelectionModel<FlatNode>(false);

  treeControl = new FlatTreeControl<FlatNode>(
    node => node.level,
    node => node.expandable
  );

  treeFlattener = new NzTreeFlattener(
    this.transformer,
    node => node.level,
    node => node.expandable,
    node => node.children
  );
  dataSource = new NzTreeFlatDataSource(this.treeControl, this.treeFlattener);


  constructor(
    private router: Router,
    private menuService: MenuService,
    private message: NzMessageService,
    private modal: NzModalService,
    private viewContainerRef: ViewContainerRef
  ) {

  }

  ngOnInit(): void {
    this.loadTree();
  }

  loadTree() {
    this.menuService.getMenuTree().subscribe(res => {
      this.dataSource.setData(res);
      this.treeControl.expandAll();
    })
  }

  openRootMenuModal(isEdit: boolean, flatmenu: FlatNode) {
    let title = isEdit ? '编辑' : '新增';
    const modal: NzModalRef = this.modal.create({
      nzTitle: title,
      nzContent: DialogInputComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzComponentParams: {
        subtitle: '根目录下的一级菜单名',
        menu_name: flatmenu.name,
        menu_icon: flatmenu.icon,
        order_num: 100,
      },
      nzFooter: [
        {
          label: '取消',
          onClick: () => modal.destroy()
        },
        {
          label: '保存',
          type: 'primary',
          onClick: componentInstance => {
            if (componentInstance!.menu_name) {
              let menu: Menu = {
                menu_name: componentInstance!.menu_name,
                menu_id: isEdit ? flatmenu.id : 0,
                parent_id: -1,
                is_leaf: false,
                menu_icon: componentInstance!.menu_icon,
                order_num: componentInstance!.order_num,
              }

              if (menu.order_num) {
                if (isNaN(menu.order_num *= 1)) {
                  menu.order_num = 100;
                }
              }
              this.saveRootMenu(menu).subscribe((el: ApiResponse) => {
                if (el.flag) {
                  modal.destroy();
                  this.loadTree();
                } else {
                  componentInstance!.subtitle = el.message;
                }
              });
            }
          }
        }
      ]
    });
  }

  addRootMenu(): void {
    let isEdit = false;
    let flatmenu: FlatNode = {
      id: 0,
      expandable: false,
      name: '',
      level: 0,
      disabled: false
    }
    this.openRootMenuModal(isEdit, flatmenu);
  }

  saveRootMenu(menu: Menu): Observable<ApiResponse> {
    return this.menuService.createMenu(menu);
  }

  gotoAddMenu(): void {
    this.router.navigateByUrl("layout/menu/form");
  }

  gotoEditMenu(): void {
    if (this.selectListSelection.isEmpty()) {
      this.message.create('error', `请选择要编辑的记录`);
      return;
    }

    let arr = this.selectListSelection.selected
    let selectedMenu: FlatNode = arr[0];
    if (selectedMenu.level === 0) {
      let isEdit = true;
      this.openRootMenuModal(isEdit, selectedMenu);
    } else {
      this.router.navigateByUrl("layout/menu/form?id=" + selectedMenu.id);
    }
  }

  // 输入目录完成
  onDirInputedOk(): void {
    this.isInputDirVisible = false;
  }

  hasChild = (_: number, node: FlatNode): boolean => node.expandable;
}
